const config = require('../config')
const rp = require('request-promise')
const crypto = require('crypto')
const { formatBody } = require('../tools')
const { apiPreFix } = config.server
const { AppID, AppKey } = config.tencentOpenAI

const getReqSign = (data, app_key) => {
  let keys = Object.keys(data).sort()
  let str = ''
  for (let i in keys) {
    if (data[keys[i]]) {
      str += `${keys[i]}=${data[keys[i]]}&`
    }
  }
  str += `app_key=${app_key}`
  return crypto.createHash('md5').update(str).digest('hex').toUpperCase()
}

module.exports = (router) => {
  /**
   * 人脸融合
   */
  router.post(`${apiPreFix}/ai/facemerge`, async  ctx => {
    let { model, image } = ctx.request.body.fields
    if (!image) {
      return ctx.body = formatBody(0, '未收到图片')
    } else {
      image = image.replace(/^data:image\/\w+;base64,/, '')
      let time_stamp = (new Date().getTime() + '').substr(0, 10)
      let data = {
        app_id: AppID,
        image,
        model,
        nonce_str: time_stamp + 'x',
        time_stamp
      }
      data = {
        app_id: '10000',
        nonce_str: '20e3408a79',
        key1: '腾讯AI开放平台',
        key2: '示例仅供参考',
        time_stamp: '1493449657'
      }
      let app_key = 'a95eceb1ac8c24ee28b70f7dbba912bf' // AppKey
      data.sign = getReqSign(data, app_key)
      // "BE918C28827E0783D1E5F8E6D7C37A61"
      console.log(data.sign)
      await rp({
        method: 'POST',
        uri: 'https://api.ai.qq.com/fcgi-bin/ptu/ptu_facemerge',
        form: data,
        json: true
      }).then(res => {
        return ctx.body = formatBody(1, 'ok', res)
      }).catch(err => {
        return ctx.body = formatBody(0, 'error', err)
      })
    }
  })
}